﻿
Imports std

Public MustInherit Class consumer
    Implements iconsumer

    Private sourceQueue As jobqueue = Nothing

    Public Sub start(ByVal sourceQueueName As String) Implements iconsumer.start
        assert(Not isemptystring(sourceQueueName))
        sourceQueue = jobqueues.at(sourceQueueName)
        sourceQueue.trigger() = AddressOf newjob
    End Sub

    Protected Overridable Sub [stop]()
    End Sub

    Public Sub iconsumer_stop() Implements iconsumer.stop
        sourceQueue.trigger() = Nothing
        [stop]()
    End Sub

    Protected MustOverride Sub workOn(ByVal j As indexedJob)

    Private Sub newjob()
        Dim job As indexedJob = Nothing
        If sourceQueue.pop(job) Then
            workOn(job)
        End If
    End Sub

    Protected Function update(ByVal job As indexedJob,
                              Optional ByVal updater As void(Of indexedJob) = Nothing) As Boolean
        Return sourceQueue.update(job, updater)
    End Function

    Public Shared Function initial(ByVal name As String,
                                   ByVal config As configParser,
                                   ByVal consumer As consumer) As Boolean
        assert(Not consumer Is Nothing)
        Dim s As String = Nothing
        If config.getparameter(name, "sourceQueue", s) Then
            consumer.start(s)
            Return True
        Else
            raiseError(errorHandle.errorType.user, "no source queue has been set in ", name)
            Return False
        End If
    End Function
End Class
